package com.stox.ui.javafx.navigator.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;

import com.stox.client.ScripClient;
import com.stox.model.AbstractModel;
import com.stox.model.Exchange;
import com.stox.model.Scrip;

public class ExchangeTreeItem extends AbstractModelTreeItem<String> {

	private Exchange exchange;
	private ScripClient scripClient;
	private List<Scrip> scrips;
	
	public ExchangeTreeItem(Exchange exchange, ScripClient scripClient) {
		super.setValue(exchange.getName());
		this.exchange = exchange;
		this.scripClient = scripClient;
	}
	
	@Override
	public AbstractModel getModel() {
		return exchange;
	}
	
	@Override
	public ObservableList<TreeItem<String>> getChildren() {
		loadScrips();
		return super.getChildren();
	}

	@Override
	public boolean isLeaf() {
		return false;
	}
	
	private void loadScrips() {
		if(null == scrips || scrips.isEmpty()) {
			scrips = scripClient.findByExchangeCode(exchange.getCode());
			Collections.sort(scrips);
			List<ScripTreeItem> scripTreeItems = new ArrayList<ScripTreeItem>(scrips.size());
			for(Scrip scrip : scrips) {
				scripTreeItems.add(new ScripTreeItem(scrip));
			}
			super.getChildren().setAll(scripTreeItems);
		}
	}
	
}
